package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 这是用户信息表
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");

        // 1.从请求中获取到blogId
        String blogId = req.getParameter("blogId");

        //如果blogId不存在或为空字符串，则创建一个id为0的用户
        if(blogId == null || blogId.equals("")) {
            String respJson = objectMapper.writeValueAsString(new User());
            resp.getWriter().write(respJson);
            System.out.println("blogId为空或者不存在");
            return;
        }

        // 2.查询数据库，根据blog中的userId来查询对应的用户数据
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if (blog == null) {
            String respJson = objectMapper.writeValueAsString(new User());
            resp.getWriter().write(respJson);
            System.out.println("参数给定的blogId不存在");
            return;
        }

        // 3.根据blog中userId来查询
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if (user == null) {
            String respJson = objectMapper.writeValueAsString(new User());
            resp.getWriter().write(respJson);
            System.out.println("该用户对应的作者不存在");
            return;
        }

        //4.把 user 对象返回给页面
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
